package com.dm.cloud.images.ws;

import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.model.Frame;
import com.dm.cloud.images.service.ImagesEndpointService;
import com.dm.cloud.images.ws.callback.ContainerLogResultCallback;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;

/**
 * 容器日志
 */
@Slf4j
@Component
@ServerEndpoint("/api/ws/docker/{nodeId}/container/{containerId}/log")
public class ContainerLogWebSocket extends AbstractWebSocket {


    private static ImagesEndpointService imagesEndpointService;

    private DockerClient client;

    @Autowired
    public void setImagesEndpointService(ImagesEndpointService imagesEndpointService){
        ContainerLogWebSocket.imagesEndpointService=imagesEndpointService;
    }

    @PostConstruct
    public void printWsStartInfo() {
        log.info("容器日志WebSocket初始化完成！");
    }


    @OnOpen
    public void onOpen(Session session) {
        final Map<String, String> param = session.getPathParameters();

        final String containerId = param.get("containerId");
        final String nodeId = param.get("nodeId");

        try {
            client=imagesEndpointService.getClientByNodeId(nodeId);
            this.init(session);
            final ResultCallback.Adapter<Frame> callback = client
                    .logContainerCmd(containerId)
                    .withFollowStream(true)
                    .withStdErr(true)
                    .withStdOut(true)
                    .withTail(500)
                    .exec(new ContainerLogResultCallback(session));
            this.addCallback(session, callback);
            session.getBasicRemote().sendText("连接成功!");
        } catch (Exception e) {
            this.onClose(session);
        }
    }

    @OnClose
    @SneakyThrows
    public void onClose(Session session) {
        try {
            super.onClose(session);
        }catch (Exception e){}
        try {
            client.close();
        }catch (Exception e){}

    }

}
